<template>
  <v-data-table
    :headers="headers"
    :items="desserts"
    sort-by="calories"
    class="elevation-1"
    :loading="loading"
    loading-text="Loading... Please wait"
  >
    <template v-slot:top>
      <v-toolbar flat>
        <v-toolbar-title>分类管理</v-toolbar-title>
        <v-divider class="mx-4" inset vertical></v-divider>
        <v-spacer></v-spacer>
        <v-dialog v-model="dialog" max-width="500px">
          <template v-slot:activator="{ on, attrs }">
            <v-btn color="primary" dark class="mb-2" v-bind="attrs" v-on="on">
              创建分类
            </v-btn>
          </template>
          <v-card>
            <v-card-title>
              <span class="text-h5">{{ formTitle }}</span>
            </v-card-title>

            <v-card-text>
              <v-container>
                <v-row>
                  <v-col cols="12" sm="6" md="12">
                    <v-text-field
                      v-model="editedItem.name"
                      label="类型名称"
                    ></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="6" md="12">
                    <v-file-input
                      accept="image/*"
                      label="封面"
                      v-model="coverImg"
                      prepend-icon=""
                      @change="getImageUrl"
                    ></v-file-input>
                  </v-col>
                  <v-col cols="12" sm="6" md="12">
                    <v-text-field
                      v-model="editedItem.desc"
                      label="描述"
                    ></v-text-field>
                  </v-col>
                </v-row>
              </v-container>
            </v-card-text>

            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn color="blue darken-1" text @click="close"> 关闭 </v-btn>
              <v-btn
                color="blue darken-1"
                text
                @click="save"
                :loading="loading"
                :disabled="loading"
              >
                保存
              </v-btn>
            </v-card-actions>
          </v-card>
        </v-dialog>
        <v-dialog v-model="dialogDelete" max-width="500px">
          <v-card>
            <v-card-title class="text-h5"
              >确定需要删除这条记录吗？</v-card-title
            >
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn color="blue darken-1" text @click="closeDelete"
                >关闭</v-btn
              >
              <v-btn color="blue darken-1" text @click="deleteItemConfirm"
                >确认</v-btn
              >
              <v-spacer></v-spacer>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-toolbar>
    </template>
    <template v-slot:item.actions="{ item }">
      <v-icon small class="mr-2" @click="editItem(item)"> mdi-pencil </v-icon>
      <v-icon small @click="deleteItem(item)"> mdi-delete </v-icon>
    </template>
    <template v-slot:no-data>
      <!-- <v-btn color="primary" @click="initialize"> Reset </v-btn> -->
    </template>
  </v-data-table>
</template>

<script>
import api from "../../axios/api";
export default {
  data: () => {
    return {
      dialog: false,
      dialogDelete: false,
      headers: [
        {
          text: "分类名称",
          align: "start",
          sortable: false,
          value: "name",
        },
        { text: "描述", value: "desc" },
        { text: "封面图", value: "coverUrl" },
        { text: "创建时间", value: "ctime" },
        { text: "修改时间", value: "utime" },
        { text: "操作", value: "actions", sortable: false },
      ],
      desserts: [],
      editedIndex: -1,
      editedItem: {
        id: "",
        name: "",
        desc: "",
        coverUrl: "",
      },
      defaultItem: {
        id: "",
        name: "",
        desc: "",
        coverUrl: "",
      },
      coverImg:null,
      loading: false,
    };
  },

  computed: {
    formTitle() {
      return this.editedIndex === -1 ? "创建分类" : "编辑分类";
    },
  },

  watch: {
    dialog(val) {
      val || this.close();
    },
    dialogDelete(val) {
      val || this.closeDelete();
    },
  },

  created() {
    this.initialize();
  },

  methods: {
    initialize() {
      this.loading = true;
      api
        .getAllWorkClass()
        .then((res) => {
          this.desserts = res.data.datas;
          this.loading = false;
        })
        .catch((e) => {
          console.error(e);
          this.loading = false;
        });
    },

    editItem(item) {
      this.editedIndex = this.desserts.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialog = true;
    },

    deleteItem(item) {
      this.editedIndex = this.desserts.indexOf(item);
      this.editedItem = Object.assign({}, item);
      this.dialogDelete = true;
    },

    deleteItemConfirm() {
      let data = {
        workClassId: this.desserts.splice(this.editedIndex, 1)[0].id,
      };
      api
        .deleteWorkClass(data)
        .then(this.initialize)
        .catch((e) => console.error(e));
      this.closeDelete();
    },

    close() {
      this.dialog = false;
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
        this.editedIndex = -1;
      });
    },

    closeDelete() {
      this.dialogDelete = false;
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem);
        this.editedIndex = -1;
      });
    },

    save() {
      if (this.editedIndex === -1) {
        // 创建分类
        if (
          this.editedItem.name != "" &&
          this.editedItem.desc != null &&
          this.editedItem.coverUrl != ""
        ) {
          let data = {
            coverUrl: this.editedItem.coverUrl,
            desc: this.editedItem.desc,
            name: this.editedItem.name,
          };
          api
            .createWorkClass(data)
            .then(() => {
              this.initialize();
              this.editedItem.coverUrl = "";
              this.coverImg = null;
              this.editedItem.desc = "";
              this.editedItem.name ="";
            })
            .catch(() => {
              alert("创建失败");
            });
        } else {
          alert("请输入完整信息");
        }
      } else {
        let data = {
          workClassId: this.editedItem.id,
          coverUrl: this.editedItem.coverUrl,
          desc: this.editedItem.desc,
          name: this.editedItem.name,
        };
        api
          .updateWorkClass(data)
          .then((datas) => {
            console.log(datas);
            this.initialize();
          })
          .catch((e) => {
            console.log(e);
            alert("修改失败");
          });
      }

      this.close();
    },
    getImageUrl(File) {
      if (File) {
        this.loading = true;
        let formdata = new FormData();
        formdata.append("image", File);
        api
          .saveCover(formdata)
          .then((res) => {
            this.editedItem.coverUrl = res.bash;
            this.loading = false;
          })
          .catch((err) => {
            console.error(err);
            alert("封面上传异常");
            this.loading = false;
          });
      } else {
        this.editedItem.coverUrl = "";
      }
    },
    saveClass() {},
  },
};
</script>

<style>
</style>